package com.thd.springboottest.async.web;

import com.thd.springboottest.async.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.Future;

/**
 * com.thd.springboottest.async.web.AsyncController
 *
 * @author: wanglei62
 * @DATE: 2022/8/31 9:35
 **/
@Controller
@RequestMapping("/async")
public class AsyncController {

    @Autowired
    private AsyncService asyncService;


    // 同步方法执行
    @RequestMapping("/test")
    @ResponseBody
    // url : http://127.0.0.1:8899/thd/async/test
    public ResponseEntity<String> test(){
        System.out.println("SUCCESS");
        return ResponseEntity.ok("SUCCESS");
    }

    // 同步方法执行
    @RequestMapping("/sync")
    @ResponseBody
    // url : http://127.0.0.1:8899/thd/async/sync
    public ResponseEntity<String> sync() throws Exception{
        asyncService.doTaskOne();
        asyncService.doTaskTwo();
        asyncService.doTaskThree();
        return ResponseEntity.ok("SUCCESS");
    }

    // 带有返回值的异步方法
    @RequestMapping("/async")
    @ResponseBody
    // url : http://127.0.0.1:8899/thd/async/async
    public ResponseEntity<String> async() throws Exception{
        asyncService.doAsyncTaskOne();
        asyncService.doAsyncTaskTwo();
        asyncService.doAsyncTaskThree();
        return ResponseEntity.ok("SUCCESS");
    }

    @RequestMapping("/returnasync")
    @ResponseBody
    // url : http://127.0.0.1:8899/thd/async/returnasync
    public ResponseEntity<String> returnasync() throws Exception{
        long start = System.currentTimeMillis();
        Future<String> t1 = asyncService.doReturnAsyncTaskOne();
        Future<String> t2 = asyncService.doReturnAsyncTaskTwo();
        Future<String> t3 = asyncService.doReturnAsyncTaskThree();

        while(true) {
            if(t1.isDone() && t2.isDone() && t3.isDone()) {
                // 三个任务都调用完成，退出循环等待
                break;
            }

            Thread.sleep(1000);

        }

        long end = System.currentTimeMillis();

        System.out.println("任务全部完成，总耗时：" + (end - start) + "毫秒");
        return ResponseEntity.ok("SUCCESS");
    }





}
